package net.esj.basic.core.engine.tools.crypt;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import net.esj.basic.utils.StringUtils;
import net.esj.basic.utils.Validators;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

public class AESCryptImpl implements Crypt {

	private String DEFAULT_SECRET_KEY = "UYHGT^&%6TF*4VPL.U^9FA!SWR3sOPe4@B*jhgFO(JNT*_)JKHaJi&Ka!lo~KOUW";

	private Logger logger = Logger.getLogger(AESCryptImpl.class);

	@Override
	public byte[] decrypt(byte[] bytes) {
		return decrypt(bytes,DEFAULT_SECRET_KEY.getBytes());
	}

	@Override
	public byte[] decrypt(byte[] bytes, byte[] decryptPass) {
		try {
			//KeyGenerator kgen = KeyGenerator.getInstance("AES");
			/*SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
			sr.setSeed(decryptPass);
			kgen.init(128, sr);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();*/
			byte[] enCodeFormat = CryptUtils.generateSecretKey(decryptPass, 16);
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(new byte[cipher.getBlockSize()]));// 初始化
			byte[] result = cipher.doFinal(bytes);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String decrypt(String content) {
		return decrypt(content,DEFAULT_SECRET_KEY.getBytes());
	}

	@Override
	public String decrypt(String content, byte[] decryptPass) {
		byte[] bytes = StringUtils.parseHexStr2Byte(content);
		byte[] decrypt = decrypt(bytes, decryptPass);
		return new String(decrypt);
	}

	@Override
	public byte[] encrypt(byte[] bytes) {
		return encrypt(bytes, DEFAULT_SECRET_KEY.getBytes());
	}

	@Override
	public byte[] encrypt(byte[] bytes, byte[] encryptPass) {
		KeyGenerator kgen;
		try {
			//kgen = KeyGenerator.getInstance("AES");
			/*SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
			sr.setSeed(encryptPass);
			kgen.init(128, sr);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();*/
			byte[] enCodeFormat = CryptUtils.generateSecretKey(encryptPass, 16);
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器
			byte[] byteContent = bytes;
			cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(new byte[cipher.getBlockSize()]));// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			logger.error("ERROR IN encrypt By AES", e);
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			logger.error("ERROR IN encrypt By AES", e);
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			logger.error("ERROR IN encrypt By AES", e);
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			logger.error("ERROR IN encrypt By AES", e);
			e.printStackTrace();
		} catch (BadPaddingException e) {
			logger.error("ERROR IN encrypt By AES", e);
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			logger.error("ERROR IN encrypt By AES", e);
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String encrypt(String content) {
		return encrypt(content, DEFAULT_SECRET_KEY.getBytes());
	}

	@Override
	public String encrypt(String content, byte[] encryptPass) {
		byte[] bytes;
		try {
			bytes = encrypt(content.getBytes("utf-8"), encryptPass);
			return StringUtils.parseByte2HexStr(bytes);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public void setDefaultSecretKey(String key) {
		if(Validators.isEmpty(key)){
			return;
		}
		this.DEFAULT_SECRET_KEY = key;
	}
	
	@Override
	public boolean checksum(byte[] bytes, byte[] encryptPass, byte[] results) {
		Assert.notNull(results);
		byte[] encrypts = encrypt(bytes, encryptPass);
		if(encrypts.length != results.length){
			return false;
		}
		for(int i=0;i<encrypts.length;i++){
			if(encrypts[i]!=results.length){
				return false;
			}
		}
		return true;
	}

	@Override
	public boolean checksum(byte[] bytes, byte[] results) {
		return checksum(bytes, DEFAULT_SECRET_KEY.getBytes(), results);
	}

	@Override
	public boolean checksum(String content, byte[] encryptPass, String results) {
		Assert.notNull(results);
		String encrypt = encrypt(content, encryptPass);
		if(encrypt.equals(results)){
			return true;
		}
		return false;
	}

	@Override
	public boolean checksum(String content, String results) {
		return checksum(content,DEFAULT_SECRET_KEY.getBytes(), results);
	}
	
	public static void main(String[] args){
		Crypt crypt = new AESCryptImpl();
		String test = "123456";
		String en = crypt.encrypt(test,"123456".getBytes());
		System.out.println(en);
		String de = crypt.decrypt(en,"123456".getBytes());
		System.out.println(de);
	}
}
